﻿#region Using

using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using WSMon.Core.Interfaces;

#endregion

namespace WSMon.Core.Checkers.Web
{
    public class SslChecker : Checker, IChecker
    {
        private readonly string _host;
        private string _logs = string.Empty;

        /// <summary>
        /// Ex: www.mysite.com
        /// </summary>
        /// <param name="host"></param>
        public SslChecker(string host)
        {
            _host = host;
        }

        #region IChecker Members

        public bool CheckOut()
        {
            try
            {
                TcpClient tcpClient = new TcpClient(_host, 443);
                var sslStream = new SslStream(tcpClient.GetStream(), false);

                try
                {
                    sslStream.AuthenticateAsClient(_host);

                    if (sslStream.RemoteCertificate != null)
                    {
                        var dtmEffective = Convert.ToDateTime(sslStream.RemoteCertificate.GetEffectiveDateString());
                        var dtmExpration = Convert.ToDateTime(sslStream.RemoteCertificate.GetExpirationDateString());

                        return (dtmEffective < DateTime.Now && DateTime.Now < dtmExpration);
                    }
                }
                catch (AuthenticationException ex)
                {
                    _logs = ex.Message;
                    return false;
                }

                _logs = "Client certification(s) not found";
                return false;
            }
            catch (Exception ex)
            {
                _logs = ex.Message;
                return false;
            }
        }

        public string GetLogs()
        {
            return _logs;
        }

        #endregion
    }
}